const api = require('../../api/api')
const util = require('../../utils/js/util')
const app = getApp()
Page({
  data: {
    keyword: '', // 关键词
    page: 1, // 页码
    list: [], // 检查项列表
    listStatus: 'loading', // 列表状态
    listSelected: [], // 已勾选的检查项列表
  },

  async onLoad() {
    this.getCheckList()
  },

  // 勾选检查项
  selectItem({ currentTarget: { dataset: { item } } }) {
    const listSelected = this.data.listSelected
    const hasItem = listSelected.findIndex(v => v.id === item.id)
    hasItem == -1 ? listSelected.push(item) : listSelected.splice(hasItem, 1)
    this.setData({ listSelected })
    this.hasSelected()
  },

  // 获取检查项列表
  async getCheckList() {
    const res = await api.getCheckList({ name: this.data.keyword, p: this.data.page })
    this.setData({
      list: this.data.page == 1 ? res.data : this.data.list.concat(res.data),
      listStatus: res.current_page == res.last_page ? 'tobottom' : res.current_page < res.last_page ? 'loading' : res.current_page > res.last_page ? 'nodata' : ''
    })
    this.hasSelected()
  },

  // 下一步
  async submitNext() {
    if (this.data.listSelected.length == 0) return util.toast('至少有一项检查项');
    wx.navigateTo({ url: '../inspectionPlan/index?selects=' + JSON.stringify(this.data.listSelected.map(v => v.id)) })
  },

  // 搜索检查项列表
  searching({ detail: { value } }) {
    this.setData({ page: 1, keyword: value, listStatus: 'loading' })
    this.getCheckList()
  },
  // 配置列表是否已勾选
  hasSelected() {
    const is = (i, v) => this.setData({ [`list[${i}].selected`]: v })
    this.data.list.forEach((v, i) => this.data.listSelected.some(v1 => v1.id === v.id) ? is(i, true) : is(i, false))
  },

  onReachBottom() {
    if (this.data.listStatus === 'loading') {
      this.setData({ page: this.data.page + 1 })
      this.getCheckList()
    }
  },
})
